package com.dayu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dayu.common.utils.R;
import com.dayu.common.vo.SkuInfoVo;
import com.dayu.gulimall.cart.feign.ProductFeignService;
import com.dayu.gulimall.cart.intercepter.CartIntercepter;
import com.dayu.gulimall.cart.service.CartService;
import com.dayu.gulimall.cart.vo.Cart;
import com.dayu.gulimall.cart.vo.UserInfoTo;
import com.dayu.gulimall.cart.vo.CartItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author dayu
 * @version 1.0
 * @email dayu007@foxmail.com
 * @date 2021/3/26 7:42
 * @description
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    public static final String CART_PREFIX = "gulimall:cart:";

    /**
     * 加入购物车  用多线程的方式执行两个线程，分别获取当前商品信息和sku的组合信息
     *
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String rst = (String) ops.get(skuId.toString());
        //缓存中没有
        if (StringUtils.isEmpty(rst)) {
            CartItem cartItem = new CartItem();
            //用多线程的方式执行两组查询
            //远程查询当前商品的信息
            CompletableFuture<Void> skuInfoFutrue = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);
                SkuInfoVo info = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setImage(info.getSkuDefaultImg());
                cartItem.setPrice(info.getPrice());
                cartItem.setSkuId(skuId);
                cartItem.setTitle(info.getSkuTitle());
                cartItem.setCount(num);
            }, executor);

            CompletableFuture<Void> attrValuesFuture = CompletableFuture.runAsync(() -> {
                // 远程查询sku的组合信息
                List<String> attrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(attrValues);
            }, executor);

            //需要等待两个线程同时完成之后在执行后面操作，阻塞在这里
            CompletableFuture.allOf(skuInfoFutrue, attrValuesFuture).get();
            String s = JSON.toJSONString(cartItem);
            ops.put(skuId.toString(), s);
            return cartItem;
        } else {
            //缓存中有这个sku，那么更新数量就行
            CartItem cartItem = JSON.parseObject(rst, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String s = JSON.toJSONString(cartItem);
            ops.put(skuId.toString(), s);
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItemInfo(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String rst = (String) ops.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(rst, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartIntercepter.threadLocal.get();
        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null) {
            //登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String cartUserKey = CART_PREFIX + userInfoTo.getUserKey();
            //如果·临时购物车数据还没有合并，先合并临时购物车的数据
            List<CartItem> tempCartItems = getCartItems(cartUserKey);
            if (!CollectionUtils.isEmpty(tempCartItems)) {
                for (CartItem cartItem : tempCartItems) {
                    //添加购物车，已经登陆，这里会自动合并到登陆后的购物车
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
//                合并购物车后清除临时购物车
                redisTemplate.delete(cartUserKey);
            }
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItemInfo(skuId);
        cartItem.setCheck(check == 1);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.put(skuId.toString(), s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItemInfo(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String hk = skuId.toString();
        ops.put(hk, s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserItems() throws ExecutionException, InterruptedException {
        Cart cart = getCart();
        List<CartItem> items = cart.getItems();
        if (CollectionUtils.isEmpty(items)) {
            return null;
        } else {
            List<CartItem> collect = items.stream().filter(item -> item.getCheck())
                    .map(item->{
                        //获取商品实时价格
                        BigDecimal skuPrice = productFeignService.getSkuPrice(item.getSkuId());
                        item.setPrice(skuPrice);
                        return item;
                    }).collect(Collectors.toList());
            return collect;
        }
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        List<Object> values = ops.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItem> collect = values.stream().map(item -> {
                String str = (String) item;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取到要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo cartInfoTo = CartIntercepter.threadLocal.get();
        String cartKey = "";
        if (cartInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + cartInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + cartInfoTo.getUserKey();
        }

        return redisTemplate.boundHashOps(cartKey);
    }
}
